// dh-doctors 云对象 - 医生信息管理
const db = uniCloud.database();
const _ = db.command;
const { autoMountHospitalId, softDelete, batchSoftDelete, getDoctorById, listDoctors, getUserById } = require('dh-common');

/**
 * 统一响应格式化辅助函数
 */
function formatResponse(code, data = null, message = 'success', extraFields = {}) {
	return {
		code,
		data,
		message,
		success: (code === 200 || code === 201),
		timestamp: Date.now(),
		...extraFields
	};
}

/**
 * 统一错误响应辅助函数
 */
function formatError(error, defaultMessage = '操作失败') {
	console.error('[dh-doctors] 错误:', error);
	return {
		code: 500,
		message: error.message || defaultMessage,
		success: false,
		timestamp: Date.now()
	};
}

/**
 * 职称等级转换文本
 */
function getTitleText(titleLevel) {
	const titleMap = {
		0: '医士',
		1: '医师',
		2: '主治医师',
		3: '副主任医师',
		4: '主任医师'
	};
	return titleMap[titleLevel] || '未知';
}

/**
 * 从 dh-common 获取医生姓名并附加职称信息
 */
async function enrichDoctorInfo(doctorData) {
	if (!doctorData || !doctorData.user_id) {
		return doctorData;
	}
	
	try {
		// 使用统一的用户查询工具获取用户信息（自动解密）
		// getUserById 已经通过 matchesRoleFilter 检查了角色（doctor 优先级 70 > 0，会通过检查）
		const userInfo = await getUserById(doctorData.user_id, 'default', false, true);
		
		if (userInfo) {
			const realName = userInfo.realName || userInfo.displayName || '未知';
			const titleText = getTitleText(doctorData.title_level);
			
			return {
				...doctorData,
				doctor_name: realName,
				title: titleText,
				title_text: titleText
			};
		}
		
		// 如果获取用户信息失败，返回默认值
		return {
			...doctorData,
			doctor_name: '未知',
			title: getTitleText(doctorData.title_level),
			title_text: getTitleText(doctorData.title_level)
		};
	} catch (error) {
		console.error('[enrichDoctorInfo] 获取医生信息失败:', error);
		// 出现异常时，返回默认值
		return {
			...doctorData,
			doctor_name: '未知',
			title: getTitleText(doctorData.title_level),
			title_text: getTitleText(doctorData.title_level)
		};
	}
}

/**
 * 批量附加医生信息
 */
async function enrichDoctorsList(doctorsList) {
	if (!Array.isArray(doctorsList) || doctorsList.length === 0) {
		return doctorsList;
	}
	
	// 获取所有唯一的用户ID
	const userIds = [...new Set(doctorsList.map(d => d.user_id).filter(Boolean))];
	
	if (userIds.length === 0) return doctorsList;
	
	try {
		// 使用dh-common模块查询医生列表
		const doctorsResult = await listDoctors({ limit: 1000 }); // 增加limit以确保能获取到所有医生
		
		// 检查查询结果
		if (doctorsResult.code !== 200) {
			console.warn(`[enrichDoctorsList] 查询医生列表失败: ${doctorsResult.msg}`);
			throw new Error(doctorsResult.msg);
		}
		
		// 过滤出我们需要的医生
		const doctors = doctorsResult.data.filter(doctor => userIds.includes(doctor._id));
		
		// 构建用户ID到姓名的映射
		const doctorMap = {};
		doctors.forEach(doctor => {
			doctorMap[doctor._id] = doctor.realName || doctor.displayName || '未知';
		});
		
		// 附加医生姓名和职称
		return doctorsList.map(doctor => ({
			...doctor,
			doctor_name: doctorMap[doctor.user_id] || '未知',
			title: getTitleText(doctor.title_level),
			title_text: getTitleText(doctor.title_level)
		}));
	} catch (error) {
		console.error('[enrichDoctorsList] 批量获取医生信息失败:', error);
		return doctorsList.map(doctor => ({
			...doctor,
			doctor_name: '未知',
			title: getTitleText(doctor.title_level),
			title_text: getTitleText(doctor.title_level)
		}));
	}
}

module.exports = {
	/**
	 * 请求前拦截 - 全局权限检查、参数验证
	 */
	async _before(methodName, params) {
		const uniIdToken = this.getUniIdToken();

		const writeMethods = ['create', 'update', 'delete', 'batch'];
		if (methodName && writeMethods.some(method => methodName.toLowerCase().includes(method))) {
			if (!uniIdToken || !uniIdToken.uid) {
				throw new Error('401|未授权的访问');
			}
		}

		if (params && typeof params === 'object') {
			for (let key in params) {
				if (typeof params[key] === 'string') {
					params[key] = params[key].trim();
				}
			}
		}
	},

	/**
 * 获取可用的医生用户列表（用于新增医生时选择用户）
 * 
 * @param {String} keyword - 搜索关键词
 * @returns {Object} { code, data, message }
 */
async getAvailableDoctorUsers(keyword = '') {
	try {
		const db = uniCloud.database();
		const _ = db.command;
		
		// 1. 获取所有已有医生档案的用户ID
		const doctorsRes = await db.collection('dh-doctors')
			.where({
				is_deleted: _.neq(true)
			})
			.field({
				user_id: true
			})
			.get();
		
		const existingUserIds = doctorsRes.data.map(d => d.user_id);
		
		// 2. 使用dh-common模块查询所有医生，并传递搜索关键词
		const doctorsResult = await listDoctors({ keyword });
		
		// 检查查询结果
		if (doctorsResult.code !== 200) {
			return formatResponse(500, null, `查询医生列表失败: ${doctorsResult.msg}`);
		}
		
		// 3. 过滤掉已有医生档案的用户
		let availableUsers = doctorsResult.data.filter(user => !existingUserIds.includes(user._id));
		
		return formatResponse(200, availableUsers, '查询成功');
	} catch (error) {
		return formatError(error, '获取可用医生用户列表失败');
	}
},

	/**
	 * 根据ID查询医生信息
	 */
	async getDoctorById(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '医生ID不能为空');
			}

			const res = await db.collection('dh-doctors').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '医生不存在');
			}
			
			// 附加医生姓名和职称信息
			const enrichedDoctor = await enrichDoctorInfo(res.data[0]);
			return formatResponse(200, enrichedDoctor);
		} catch (error) {
			return formatError(error, '获取医生信息失败');
		}
	},

	/**
	 * 根据用户ID查询医生信息
	 */
	async getDoctorByUserId(userId) {
		try {
			if (!userId) {
				return formatResponse(400, null, '用户ID不能为空');
			}

			const res = await db.collection('dh-doctors').where({ user_id: userId }).get();
			if (res.data.length === 0) {
				return formatResponse(200, null);
			}
			
			// 附加医生姓名和职称信息
			const enrichedDoctor = await enrichDoctorInfo(res.data[0]);
			return formatResponse(200, enrichedDoctor);
		} catch (error) {
			return formatError(error, '获取医生信息失败');
		}
	},

	/**
 * 获取医生列表
 */
async listDoctors(query = {}, skip = 0, limit = 20) {
	try {
		if (typeof query !== 'object' || query === null || Array.isArray(query)) {
			query = {};
		}
		skip = parseInt(skip) || 0;
		limit = parseInt(limit) || 20;
		
		// 构建查询条件
		let whereCondition = {
			is_deleted: false  // 默认不显示已删除记录
		};
		
		// 如果有职称等级条件
		if (query.title_level !== undefined) {
			whereCondition.title_level = query.title_level;
		}
		
		// 如果有医院ID条件（支持字符串或对象格式）
		if (query.hospital_id) {
			// 兼容字符串和对象格式的查询
			whereCondition.hospital_id = query.hospital_id;
		}
		
		// 如果有工作状态条件
		if (query.working_status !== undefined) {
			whereCondition.working_status = query.working_status;
		}
		
		// 获取总记录数
		const countRes = await db.collection('dh-doctors')
			.where(whereCondition)
			.count();
		
		// 获取分页数据
		const res = await db.collection('dh-doctors')
			.where(whereCondition)
			.skip(skip)
			.limit(limit)
			.orderBy('create_time', 'desc')
			.get();
		
		// 批量附加医生姓名和职称信息
		const enrichedDoctors = await enrichDoctorsList(res.data);
		
		// 如果有关键词搜索，在附加姓名后再进行过滤
		let filteredDoctors = enrichedDoctors;
		if (query.keyword && query.keyword.trim()) {
			const keyword = query.keyword.trim().toLowerCase();
			filteredDoctors = enrichedDoctors.filter(doctor => 
				doctor.doctor_name?.toLowerCase().includes(keyword) ||
				doctor.title?.includes(keyword) ||
				doctor.specialties?.some(s => s.includes(keyword))
			);
		}
		
		return formatResponse(200, filteredDoctors, 'success', { count: countRes.total });
	} catch (error) {
		return formatError(error, '获取医生列表失败');
	}
},

	/**
	 * 创建医生信息
	 */
	async createDoctor(data) {
		try {
			if (!data.user_id || data.title_level === undefined) {
				return formatResponse(400, null, '用户ID和职称等级不能为空');
			}

			// 准备医生数据
			let doctorData = {
				user_id: data.user_id,
				title_level: parseInt(data.title_level),
				photo: data.photo || null,
				license_no: data.license_no || '',
				license_valid_until: data.license_valid_until || null,
				specialties: Array.isArray(data.specialties) ? data.specialties : [],
				education_background: data.education_background || '',
				years_experience: parseInt(data.years_experience) || 0,
				introduction: data.introduction || '',
				consultation_fee: parseFloat(data.consultation_fee) || 0,
				rating: 0,
				total_consultations: 0,
				working_status: data.working_status !== undefined ? data.working_status : 0,
				is_deleted: false,  // 软删除字段，默认未删除
				create_time: Date.now(),
				update_time: Date.now()
			};

			// 🏥 自动挂载医院ID（单一医院系统特性）
			doctorData = await autoMountHospitalId(doctorData);

			const res = await db.collection('dh-doctors').add(doctorData);
			return formatResponse(201, { _id: res.id }, '医生信息创建成功');
		} catch (error) {
			return formatError(error, '创建医生失败');
		}
	},

	/**
	 * 更新医生信息
	 */
	async updateDoctor(id, data) {
		try {
			if (!id) {
				return formatResponse(400, null, '医生ID不能为空');
			}

			const updateData = {};
			
			// 只更新允许修改的字段
			if (data.title_level !== undefined) updateData.title_level = parseInt(data.title_level);
			if (data.photo !== undefined) updateData.photo = data.photo;
			if (data.hospital_id !== undefined) updateData.hospital_id = data.hospital_id;
			if (data.license_no !== undefined) updateData.license_no = data.license_no;
			if (data.license_valid_until !== undefined) updateData.license_valid_until = data.license_valid_until;
			if (data.specialties !== undefined) updateData.specialties = Array.isArray(data.specialties) ? data.specialties : [];
			if (data.education_background !== undefined) updateData.education_background = data.education_background;
			if (data.years_experience !== undefined) updateData.years_experience = parseInt(data.years_experience) || 0;
			if (data.introduction !== undefined) updateData.introduction = data.introduction;
			if (data.consultation_fee !== undefined) updateData.consultation_fee = parseFloat(data.consultation_fee) || 0;
			if (data.working_status !== undefined) updateData.working_status = data.working_status;
			
			updateData.update_time = Date.now();

			await db.collection('dh-doctors').doc(id).update(updateData);
			return formatResponse(200, null, '医生信息更新成功');
		} catch (error) {
			return formatError(error, '更新医生失败');
		}
	},

	/**
	 * 删除医生信息
	 */
	async deleteDoctor(id, reason = '') {
		try {
			if (!id) {
				return formatResponse(400, null, '医生ID不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await softDelete('dh-doctors', id, uniIdToken?.uid || '', reason);
			
			if (result.code === 200) {
				return formatResponse(200, null, '医生已移至回收站');
			} else {
				return formatResponse(result.code, null, result.message);
			}
		} catch (error) {
			return formatError(error, '删除医生失败');
		}
	},

	/**
	 * 批量更新医生信息
	 */
	async batchUpdateDoctors(updates) {
		try {
			if (!Array.isArray(updates) || updates.length === 0) {
				return formatResponse(400, null, '更新数据不能为空');
			}

			const promises = updates.map(item =>
				db.collection('dh-doctors').doc(item._id).update({
					...item,
					update_time: Date.now()
				})
			);

			await Promise.all(promises);
			return formatResponse(200, null, `批量更新${updates.length}条记录成功`);
		} catch (error) {
			return formatError(error, '批量更新失败');
		}
	},

	/**
	 * 批量删除医生信息
	 */
	async batchDeleteDoctors(ids, reason = '') {
		try {
			if (!Array.isArray(ids) || ids.length === 0) {
				return formatResponse(400, null, 'ID列表不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await batchSoftDelete('dh-doctors', ids, uniIdToken?.uid || '', reason);
			
			return formatResponse(result.code, result.data, result.message);
		} catch (error) {
			return formatError(error, '批量删除失败');
		}
	},

	/**
	 * 更新医生评分
	 */
	async updateDoctorRating(id, rating, totalConsultations) {
		try {
			if (!id) {
				return formatResponse(400, null, '医生ID不能为空');
			}

			await db.collection('dh-doctors').doc(id).update({
				rating: rating,
				total_consultations: totalConsultations,
				update_time: Date.now()
			});

			return formatResponse(200, null, '评分更新成功');
		} catch (error) {
			return formatError(error, '更新评分失败');
		}
	},

	/**
 * 获取出诊中的医生列表
 */
async getActiveDoctors(hospitalId = null, skip = 0, limit = 20) {
	try {
		let query = { working_status: 0 }; // 0-出诊中
		if (hospitalId) {
			query.hospital_id = hospitalId;
		}

		// 获取总记录数
		const countRes = await db.collection('dh-doctors')
			.where(query)
			.count();
		
		// 获取分页数据
		const res = await db.collection('dh-doctors')
			.where(query)
			.skip(skip)
			.limit(limit)
			.orderBy('rating', 'desc')
			.get();

		// 批量附加医生姓名和职称信息
		const enrichedDoctors = await enrichDoctorsList(res.data);

		return formatResponse(200, enrichedDoctors, 'success', { count: countRes.total });
	} catch (error) {
		return formatError(error, '获取出诊医生失败');
	}
}
};

